package com.qf.controller;

import com.google.gson.Gson;
import com.qf.entity.Student;
import com.qf.service.StudentService;
import lombok.SneakyThrows;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/pick")
public class PickNameServlet extends HttpServlet {
    public static final String FAIR = "1";
    public static final String UNFAIR = "2";
    private StudentService ps = new StudentService();
    @Override
    public void service(HttpServletRequest req, HttpServletResponse resp){
        //判断请求方法
        String type = req.getParameter("method");
        switch (type){
            case "pickName":
                pickName(req,resp);
                break;
            case "getCalledCount":
                getCalledCount(req, resp);
                break;
        }
    }

    /**
     * 点名（公平和非公平）
     * @param req
     * @param resp
     */
    @SneakyThrows
    public void pickName(HttpServletRequest req, HttpServletResponse resp){
        String type = req.getParameter("type");
        //type=1表示公平点名  type=2表示不公平点名
        if (type.equals("1")){
            String s = ps.PickName(type);
            resp.setContentType("text/html;charset=utf-8");
            resp.getWriter().write("公平点名：" +s);
        }else {
            type = UNFAIR;
            String s = ps.PickName(type);
            resp.setContentType("text/html;charset=utf-8");
            resp.getWriter().write("不公平点名：" + s);
        }
    }

    /**
     * 查询所有学生被点次数的web接口
     * @param req
     * @param resp
     */
    @SneakyThrows
    public void getCalledCount(HttpServletRequest req, HttpServletResponse resp){
        List<Student> studentList = ps.getCount();
        //通过Gson依赖直接将list集合转换为json格式
        String s = new Gson().toJson(studentList);
        resp.setContentType("text/html;charset=utf-8");
        resp.getWriter().write(s);
    }
}
